package com.bucket.cloud.system.mq;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bucket.cloud.common.core.constants.QueueConstants;
import com.bucket.cloud.common.core.security.http.OpenRestTemplate;
import com.bucket.cloud.system.api.model.SystemInterface;
import com.bucket.cloud.system.service.GatewayInterfaceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;

import java.util.concurrent.TimeUnit;

/**
 * 动态刷新Api
 *
 * @author cyq
 */
@Configuration
@Slf4j
public class ResourceScanHandler {

    @Autowired
    private GatewayInterfaceService gatewayInterfaceService;
    @Autowired
    private OpenRestTemplate restTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    private final static String SCAN_API_RESOURCE_KEY_PREFIX = "scan_api_resource:";

    /**
     * 接收API资源扫描消息
     */
    @RabbitListener(queues = QueueConstants.QUEUE_SCAN_API_RESOURCE)
    public void ScanApiResourceQueue(@Payload JSONObject resource) {
        try {
            String serviceId = resource.getString("application");
            String key = SCAN_API_RESOURCE_KEY_PREFIX + serviceId;
            Object object = redisTemplate.opsForValue().get(key);
            if (object != null) {
                // 3分钟内未失效,不再更新资源
                return;
            }
            JSONArray array = resource.getJSONArray("mapping");
            for (int i = 0; i < array.size(); i++) {
                JSONObject jsonObject = array.getJSONObject(i);
                try {
                    SystemInterface api = jsonObject.toJavaObject(SystemInterface.class);
                    api.setIntOpen(2);
                    api.setIntPersist(1);
                    gatewayInterfaceService.addApiUseMerge(api);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("添加资源error:", e.getMessage());
                }
            }
            if (array != null && array.size() > 0) {
                redisTemplate.opsForValue().set(key, array.size(), 3L, TimeUnit.MINUTES);
                // TODO 刷新路由
//                restTemplate.refreshGateway();
            }
        } catch (Exception e) {
            log.error("error:", e);
        }
    }
}
